package com.kakarote.ids.provider.utils;

import com.alicp.jetcache.CacheManager;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.template.QuickConfig;
import com.kakarote.common.entity.UserInfo;
import com.kakarote.ids.provider.common.OAuthProperties;
import com.kakarote.ids.provider.service.DeptService;
import com.kakarote.ids.provider.service.UserService;

import java.time.Duration;
import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties({OAuthProperties.class})
public class CacheAutoConfiguration {
    @Autowired
    private CacheManager cacheManager;

    @Autowired(required = false)
    private UserService userService;

    @Autowired(required = false)
    private DeptService deptService;

    @PostConstruct
    public void init() {
        UserCacheUtil.userCache = this.cacheManager.getOrCreateCache(QuickConfig.newBuilder("").expire(Duration.ofDays(3L)).cacheType(CacheType.BOTH).build());
        UserCacheUtil.deptCache = this.cacheManager.getOrCreateCache(QuickConfig.newBuilder("").expire(Duration.ofDays(3L)).cacheType(CacheType.BOTH).build());
        if (this.userService != null)
            UserCacheUtil.userInfoCacheLoader = (key -> (UserInfo) this.userService.queryUserInfoByUserId(key).getData());
        if (this.deptService != null)
            UserCacheUtil.deptCacheLoader = (key -> (String) this.deptService.queryDeptNameByDeptId(key).getData());
    }
}
